package com.example.springcloud.controller;

import com.example.springcloud.dao.PaymentDao;
import com.example.springcloud.entities.CommonResult;
import com.example.springcloud.entities.CommonResultEnum;
import com.example.springcloud.entities.Payment;
import com.mysql.jdbc.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentDao paymentDao;

    @Value("${server.port}")
    private String port;

    @GetMapping("{id}")
    public CommonResult getPayment(@PathVariable(value = "id") Long id) {
        Payment payment = paymentDao.getPaymentById(id);
        log.info("端口号：" + port + ", 查询结果：" + payment);
        if (payment != null) return CommonResult.success(payment);
        else return CommonResult.error(CommonResultEnum.GET_ERROR);
    }

    @PostMapping
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentDao.create(payment);
        log.info("端口号：" + port + ", 插入结果： " + result);
        if (result > 0) return CommonResult.success(result);
        else return CommonResult.error(CommonResultEnum.CREATE_ERROR, payment);
    }

    @GetMapping("/lb")
    public String getServerPort() {
        return port;
    }

    @GetMapping("/feign/timeout")
    public String timeoutTest() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }
}
